import hashlib, base64, os

from flask import request, abort

from uuid import uuid4

from models import User, db

from ..baseMethodView import BaseMethodView


# 注册
class Register(BaseMethodView):
    def post(self):
        args = request.json
        if args:
            name = args.get('name', None)
            account = args.get('account', None)
            pwd = args.get('password', None)
            if name and account and pwd:
                try:
                    u = User.query.filer(User.account == account).first()
                    if u:
                        self.set_data(
                            dict(flag=-1)
                        )
                    else:
                        m = hashlib.md5()
                        m.update(pwd.encode('utf8'))
                        token = base64.b32encode(os.urandom(20))
                        user = User()
                        user.guid = '{}'.format(uuid4())
                        user.name = name
                        user.password = pwd
                        user.token = token
                        user.MD5PWD = m.hexdigest()
                        db.session.add(user)
                        db.session.commit()
                        self.set_data(dict(flag=1, token=token))
                except Exception as e:
                    print('{}'.format(e))
                    self.set_data(dict(flag=0))
                return self.result()
            else:
                abort(403)
        else:
            abort(403)
